package limousine.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.nio.ByteBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.sql.Date;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Properties;
import java.util.UUID;

public class Func {
    /*public String convertFullDateToTimeStampStr(String full_date){//Mon Nov 24 00:00:01 ICT 2008
    // String full_date = "Mon Nov 24 00:00:01 ICT 2008";
    String[] month = {"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec",};
    String[] value = {"01","02","03","04","05","06","07","08","09","10","11","12"};
    String [] tmp = full_date.split(" ");
    StringBuffer sb = new StringBuffer();
    sb.append(tmp[5]).append("-");
    for(int i=0;i<month.length;i++){
    if(tmp[1].equals(month[i])){
    sb.append(value[i]);
    break;
    }
    }
    sb.append("-").append(tmp[2]).append(" ").append(tmp[3]);        
    return sb.toString();
    }
     */

    public String getCurrentDate() {
        StringBuffer ud = new StringBuffer();
        NumberFormat formatter = new DecimalFormat("00");
        Calendar rightNow = Calendar.getInstance();
        ud.append(formatter.format(rightNow.get(Calendar.YEAR)));
        ud.append(formatter.format(rightNow.get(Calendar.MONTH) + 1));
        ud.append(formatter.format(rightNow.get(Calendar.DAY_OF_MONTH)));
        return ud.toString();
    }

    public boolean checkTimeOverTheDay(String strDate, int day) {// yyyy-MM-dd HH:mm:ss
        String curDate = getCurrentDate();
        //System.out.println("curDate="+curDate);
        strDate = strDate.substring(0, 4) + strDate.substring(5, 7) + strDate.substring(8, 10);
        if (Integer.parseInt(curDate) - Integer.parseInt(strDate) > day) {
            return true;
        }
        return false;
    }

    public String getUnitSize(String sizeByte) {
        String out = "";
        double d = 0;
        int length = sizeByte.length();
        if (length <= 3) {//byte
            //System.out.println("SIZE ["+sizeByte+"]b");
            return sizeByte + " B";
        } else if (length <= 6) {//kb
            d = Double.parseDouble(sizeByte) / 1000;
            out = d + "";
            int a = out.indexOf(".");
            if (a != -1) {
                if (out.length() - a > 3) {
                    out = out.substring(0, a + 3);
                }
            }
            //System.out.println("SIZE ["+out+"]Kb");
            return out + " KB";
        } else {//mb
            d = Double.parseDouble(sizeByte) / 1000000;
            out = d + "";
            int a = out.indexOf(".");
            if (a != -1) {
                if (out.length() - a > 3) {
                    out = out.substring(0, a + 3);
                }
            }
        }
        //System.out.println("SIZE ["+out+"]Mb");
        return out + " MB";
    }

    public String getPercent(double x) {
        NumberFormat nf = NumberFormat.getPercentInstance();
        System.out.println(nf.format(x));
        return nf.format(x);
    }

    public String convertMonthYearToDisplayEn(String str_date) {// yyyy-MM
        str_date = (str_date == null) ? "" : str_date;
        if (str_date.length() != 7) {//2011-01
            return str_date;
        }        
        String[] month = {"January", "February", "March", "April", "May", "June", "July",
            "August", "September", "October", "November", "December",};
        String tmp = str_date.substring(5, 7);// get month number
        int m = Integer.parseInt(tmp);
        tmp = month[--m] + " " + str_date.substring(0, 4);
        return tmp;//December 2011
    }

    public String convertDateTimeToDisplayEn(String str_date) {// yyyy-MM-dd HH:mm:ss
        str_date = (str_date == null) ? "" : str_date;
        if (str_date.length() != 10) {//2011-01-01
            if (str_date.length() < 19) {
                return str_date;
            }
        }
        str_date = removeMilliSec(str_date);
        String[] month = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul",
            "Aug", "Sep", "Oct", "Nov", "Dec",};
        String tmp = str_date.substring(5, 7);// get month number
        int m = Integer.parseInt(tmp);
        tmp = str_date.substring(8, 10) + " " + month[--m] + ". " + str_date.substring(0, 4);
        return tmp;//10 Dec. 2011
    }

    public String convertDateTimeToDisplayTh1(String str_date) {// yyyy-MM-dd HH:mm:ss
        str_date = (str_date == null) ? "" : str_date;
        if (str_date.length() != 10) {//2011-01-01
            if (str_date.length() < 19) {
                return str_date;
            }
        }
        str_date = removeMilliSec(str_date);
        String[] month = {"มกราคม", "กุมภาพันธ์", "มีนาคม", "เมษายน", "พฤษภาคม", "มิถุนายน", "กรกฏาคม",
            "สิงหาคม", "กันยายน", "ตุลาคม", "พฤศจิกายน", "ธันวาคม",};
        String tmp = str_date.substring(5, 7);// get month number
        int m = Integer.parseInt(tmp);
        tmp = str_date.substring(8, 10) + " " + month[--m] + " " + (Integer.parseInt(str_date.substring(0, 4)) + 543);
        return tmp;//10 มกราคม 2554
    }

    public String convertDateTimeToDisplayTh2(String str_date) {// yyyy-MM-dd HH:mm:ss
        str_date = (str_date == null) ? "" : str_date;
        if (str_date.length() != 10) {//2011-01-01
            if (str_date.length() < 19) {
                return str_date;
            }
        }
        str_date = removeMilliSec(str_date);
        String[] month = {"ม.ค.", "ก.พ.", "มี.ค.", "เม.ย.", "พ.ค.", "มิ.ย.", "ก.ค.",
            "ส.ค.", "ก.ย.", "ต.ค.", "พ.ย.", "ธ.ค.",};
        String tmp = str_date.substring(5, 7);// get month number
        int m = Integer.parseInt(tmp);
        tmp = str_date.substring(8, 10) + " " + month[--m] + " " + (Integer.parseInt(str_date.substring(0, 4)) + 543);
        return tmp;//10 มกราคม 2554
    }

    public String convertDateTimeToDisplayTh3(String str_date) {// yyyy-MM-dd HH:mm:ss
        str_date = (str_date == null) ? "" : str_date;
        if (str_date.length() != 10) {//2011-01-01
            if (str_date.length() < 19) {
                return str_date;
            }
        }
        str_date = removeMilliSec(str_date);
        String tmp = "";
        tmp = str_date.substring(8, 10) + "." + str_date.substring(5, 7) + "." + (Integer.parseInt(str_date.substring(0, 4)) + 543 + " | ");
        tmp += str_date.substring(10, 16) + " น.";
        return tmp;//25.04.2554 | 16:45 น.
    }

    public String removeMilliSec(String date_str) {
        if (date_str != null) {
            if (date_str.length() > 19) {
                date_str = date_str.substring(0, 19);
            }
        } else {
            return "";
        }
        return date_str;
    }

    public String convertToDDMMYYYY(String seperater, String str) {// yyyy-MM-dd HH:mm:ss
        if (str.length() >= 10) {
            str = str.substring(8, 10) + seperater + str.substring(5, 7) + seperater + str.substring(0, 4);
        }
        return str;
    }

    public String convertToDDMMYYYY(String str) {// yyyy-MM-dd HH:mm:ss
        if (str.length() >= 10) {
            str = str.substring(8, 10) + "/" + str.substring(5, 7) + "/" + str.substring(0, 4);
        }
        // System.out.println("STR "+str);
        return str;
    }

    public String convertToYYYY_MM_DD(String str) {// dd/mm/yyyy
        str = str.substring(6, 10) + "-" + str.substring(3, 5) + "-" + str.substring(0, 2);
        // System.out.println("STR "+str);
        return str;
    }

    public String displayTextByLenght(String str, int lenght) {
        str = str.replaceAll("<[^>]*>", "");//xml tag
        str = str.replaceAll("&[a-z]*;", "");//&___;
        if (str.length() > lenght) {
            str = str.substring(0, lenght) + "...";
        }
        return str;
    }

    public String displayTextDetailList(String strHeader, int maxHeader, String strDetail, int maxDetail, int defaultDetail) {
        if (strHeader.length() > maxHeader) {
            strDetail = displayTextByLenght(strDetail, maxDetail);
        } else {
            strDetail = displayTextByLenght(strDetail, defaultDetail);
        }
        return strDetail;
    }

    public void startDelay(int time) {//1,2,3 sec
        try {
            Thread.sleep(time * 1000); // do nothing for 1000 miliseconds (1 second)
            System.out.println("---Delay " + time + " sec");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public String convertFullDateToTimeStampStr(java.util.Date full_date) {//Mon Nov 24 00:00:01 ICT 2008
        // Format the current time.
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = formatter.format(full_date);
        // System.out.println("VVV111 " + dateString);
        // Parse the previous string back into a Date.
//		 ParsePosition pos = new ParsePosition(0);
//		 Date currentTime_2 = formatter.parse(dateString, pos);
//                 System.out.println("VVV222 " +currentTime_2);
        return dateString;
    }

    public long convertFullDateToLong(java.util.Date full_date) {//Mon Nov 24 00:00:01 ICT 2008
        // Format the current time.
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = formatter.format(full_date);
        try {
            // DateFormat dateFormat;
            java.util.Date date;
            // formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            date = formatter.parse(dateString);
            return date.getTime();
        } catch (Exception e) {
            System.out.println("Exception :" + e);
        }
        return 0;
    }

    public Timestamp getTimestamp() {
//        SimpleDateFormat fm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        String thistime = fm.format(Calendar.getInstance().getTime());
//        Timestamp time = Timestamp.valueOf(thistime);

        java.util.Date date = new java.util.Date();
        //System.out.println(new Timestamp(date.getTime()));
        return new Timestamp(date.getTime());
//        return time;
    }

    public String getTimestampStr() {
        SimpleDateFormat fm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String thistime = fm.format(Calendar.getInstance().getTime());
        Timestamp time = Timestamp.valueOf(thistime);
        return time.toString();
    }

    public String removeTime(String dateStr) {//yyyy-MM-dd HH:mm:ss
        if (dateStr.length() < 10) {
            return dateStr;
        }
        return dateStr.substring(0, 10);
    }

    public String removeDate(String dateStr) {//yyyy-MM-dd HH:mm:ss
        if (dateStr.length() < 10) {
            return dateStr;
        }
        return dateStr.substring(11);
    }

    public Timestamp changeToTimestamp(String date) {
        if (date.length() == 0) {
            return null;
        }
        Timestamp time = Timestamp.valueOf(date);
        return time;
    }

    public long dateToLong(String str_date) {
        try {
            DateFormat formatter;
            java.util.Date date;
            formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            date = formatter.parse(str_date);
            return date.getTime();
        } catch (Exception e) {
            System.out.println("Exception :" + e);
        }
        return 0;
    }

    public Date getDate() {
        SimpleDateFormat fm = new SimpleDateFormat("yyyy-MM-dd");
        String thisDate = fm.format(Calendar.getInstance().getTime());
        //Timestamp time = Timestamp.valueOf(thistime);
        Date date = Date.valueOf(thisDate);
        return date;
    }

    public Date getDate_(long x) {
        SimpleDateFormat fm = new SimpleDateFormat("yyyy-MM-dd HH:mm:dd");
        String thisDate = fm.format(x);
        //Timestamp time = Timestamp.valueOf(thistime);
        Date date = Date.valueOf(thisDate);
        return date;
    }

    public String getDateStr() {
        SimpleDateFormat fm = new SimpleDateFormat("yyyy-MM-dd");
        String thisDate = fm.format(Calendar.getInstance().getTime());
        //Timestamp time = Timestamp.valueOf(thistime);
        Date date = Date.valueOf(thisDate);
        return date.toString();
    }

    public long getLongDate() {
        long thistime = Calendar.getInstance().getTimeInMillis();
        return thistime;
    }

    public String longDateToString(long longDate) {
        Date d = new Date(longDate);
        SimpleDateFormat fm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String thisDate = fm.format(d);
        return thisDate;
    }

    public Date changeToDate(String date) {
        Date thisdate = Date.valueOf(date);
        return thisdate;
    }
    public Date javaDateToSqlDate(java.util.Date date) {
        return new java.sql.Date(date.getTime());
    }
    public String db2UTF(String str) {
        try {
            byte[] rawByteForm = str.getBytes("UTF-8");
            str = new String(rawByteForm, "UTF-8");
        } catch (UnsupportedEncodingException e) {
        }
        return str;
    }

    public String jsp2UTF(String str) {
        try {
            byte[] rawByteForm = str.getBytes("ISO-8859-1");
            str = new String(rawByteForm, "UTF-8");
        } catch (UnsupportedEncodingException e) {
        }
        return str;
    }
    public String jsp2Charset(String str,String charset) {
        try {
            byte[] rawByteForm = str.getBytes("ISO-8859-1");
            str = new String(rawByteForm,charset);
        } catch (UnsupportedEncodingException e) {
        }
        return str;
    }

    public String protectNullString(String value) {// optimize data
        value = (value == null) ? "" : value.trim();
        return jsp2UTF(value);
    }
    public String protectNullString(String value,String charset) {// optimize data
        value = (value == null) ? "" : value.trim();

        if(!isCharset(value.getBytes(),charset)){
            //System.out.println("Not_UTF-8");
            return jsp2Charset(value,charset);
        }
        return value;
    }
    public boolean isCharset(byte[] b, String csnam) {
        CharsetDecoder cd =  Charset.availableCharsets().get(csnam).newDecoder();
        try {
            cd.decode(ByteBuffer.wrap(b));
        } catch (CharacterCodingException e) {
            return false;
        }
        return true;
    }

    public static String Unicode2ASCII(String unicode) {
        StringBuffer ascii = new StringBuffer(unicode);
        int code;
        for (int i = 0; i < unicode.length(); i++) {
            code = (int) unicode.charAt(i);
            if ((0xE01 <= code) && (code <= 0xE5B)) {
                ascii.setCharAt(i, (char) (code - 0xD60));
            }
        }
        return ascii.toString();
    }

    public String randomStr(int length) {
        UUID uuid = UUID.randomUUID();
        String myRandom = uuid.toString();
        return myRandom.substring(0,length);
    }

    public String[] sepString(String data, String sep) {
        boolean next = true;
        int count = 1;//default
        String mem = data;
        while (next) {
            int p = mem.indexOf(sep);
            if (p != -1) {
                count++;
                mem = mem.substring(p + 1);
            } else {
                next = false;
            }
        }
        String[] after = new String[count];
        mem = data;
        for (int i = 0; i < after.length; i++) {
            int p = mem.indexOf(sep);
            if (p != -1) {
                count++;
                after[i] = mem.substring(0, p);
                mem = mem.substring(p + 1);
            } else {
                after[i] = mem;
            }

        }
        return after;
    }

    public String getDateLongNumberStr() {
        StringBuffer ud = new StringBuffer();
        NumberFormat formatter = new DecimalFormat("00");
        Calendar rightNow = Calendar.getInstance();
        ud.append(formatter.format(rightNow.get(Calendar.DAY_OF_MONTH)));
        ud.append(formatter.format(rightNow.get(Calendar.MONTH) + 1));
        ud.append(formatter.format(rightNow.get(Calendar.YEAR)));
        ud.append(formatter.format(rightNow.get(Calendar.HOUR_OF_DAY)));
        ud.append(formatter.format(rightNow.get(Calendar.MINUTE)));
        return ud.toString();
    }

    public static String getNumberRandom() {
        StringBuffer ui = new StringBuffer();
        ui.append(Math.random());
        int i = ui.indexOf(".");
        if (i > -1) {
            return ui.substring(i + 1, i + 4);
        }
        String userid = (ui.toString().length() > 3) ? ui.toString().substring(
                0, 3) : ui.toString();
        return userid;
    }

    public String genCode() {
        StringBuffer str = new StringBuffer("");
        str.append(getDateLongNumberStr());
        str.append(getNumberRandom());
        return str.toString().trim();
    }

    public String addSlash(String str, int num) {
        String out = "";
        String slash = "";
        for (int i = 1; i <= num; i++) {
            slash += "\\";
        }
        String[] v = this.sepString(str, "\\");
        for (int i = 1; i < v.length; i++) {
            out += slash + v[i];
        }
        return out;
    }

    public String replaceString(String scr, String replace, String find) {
        scr = scr.replaceAll(find, replace);
        return scr;
    }

    public String replace(String str, String pattern, String replace) {
        int s = 0;
        int e = 0;
        StringBuffer result = new StringBuffer();
        while ((e = str.indexOf(pattern, s)) >= 0) {
            result.append(str.substring(s, e));
            result.append(replace);
            s = e + pattern.length();
        }
        result.append(str.substring(s));
        return result.toString();
    }

    public String getLastString(String str, String find) {
        int x = str.lastIndexOf(find);
        if (x != -1) {
            str = str.substring(x + 1);
        }
        return str;
    }

    public boolean checkMatchProperty(String fileName, String word) {
        Properties prop = new Properties();
        try {
            prop.load(getClass().getResourceAsStream("/" + fileName + ".properties"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (prop.getProperty(word) != null) {
            return true;
        }
        return false;
    }

    public Properties getPropertyFromfile(String filename) {
        Properties prop = new Properties();
        try {
            prop.load(getClass().getResourceAsStream("/" + filename + ".properties"));
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return prop;
    }

    public String getPropertyValue(Properties prop, String name) {
        if (prop.getProperty(name) != null) {
            return prop.getProperty(name);
        }
        return null;
    }

    public void backProcess(String url) throws Exception {
        URL yahoo = new URL(url);
        URLConnection yc = yahoo.openConnection();
        BufferedReader in = new BufferedReader(
                new InputStreamReader(
                yc.getInputStream()));
        /*String inputLine;

        while ((inputLine = in.readLine()) != null)
        System.out.println(inputLine);
        in.close();
         */
    }

    public void callExtarnalService(String url) throws Exception {
        URL yahoo = new URL(url);
        URLConnection yc = yahoo.openConnection();
        BufferedReader in = new BufferedReader(
                new InputStreamReader(yc.getInputStream()));
    }

    public String putAnd(int n) {
        if (n > 0) {
            return " and ";
        }
        return "";
    }

    public String putOr(int n) {
        if (n > 0) {
            return " or ";
        }
        return "";
    }

    public String getCondition(int i) {
        if (i > 0) {
            return " and ";
        } else {
            return " where ";
        }
    }

    public String convertStar(String str) {
        String out = str.trim();
        out = out.replace('*', '%');
        if (out.indexOf("%") != -1) {// found
            out = " like \'" + out + "\' ";
        } else {
            out = " = \'" + out + "\' ";
        }
        return out;
    }

    public boolean isNumber(String str) {
        int length = str.trim().length();
        if (length == 0) {
            return false;
            // check that all characters are digits, ., -, or ""
        }
        for (int i = 0; i < length; ++i) {
            char new_key = str.charAt(i); // cycle through characters
            if (((new_key < '0') || (new_key > '9')) && !(new_key == ' ')) {
                // System.out.println("not number");
                return false;
            }
        }
        return true;
    }

    public String inputStreamToString(InputStream in) {
        String data = "";
        try {
            int length = in.available();
            byte[] buf = new byte[length];
            int total = 0;
            while (total < length) {
                int c = in.read(buf, total, length - total);
                if (c < 0) {
                    break;
                }
                total += c;
            }
            data = new String(buf, 0, total, "UTF-8");
            in.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return data.trim();
    }

    public InputStream getStream(String surl) {// Create a URLConnection object
        // for a URL
        try {
            URL url = new URL(surl);
            URLConnection conn = url.openConnection();
            HttpURLConnection httpConn = (HttpURLConnection) conn;
            //httpConn.setRequestProperty("username", this.USERNAME);
            //httpConn.setRequestProperty("password", this.PASSWORD);
            httpConn.connect();
            return httpConn.getInputStream();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public String createFromConfirmRemove(String onclickurl, String item) {
        onclickurl += "&confirm=true";
        StringBuffer sb = new StringBuffer();
        sb.append("  <table class=\"tableForm\">");
        sb.append("    <tr height=\"10\"><td colspan=\"2\"></td></tr>");
        sb.append("    <tr><td width=\"10%\" align=\"center\"><img src=\"./img/attention.gif\" /></td>");
        sb.append("        <td class=\"textFormLabel\">");
        sb.append("         Your " + item.trim() + " have relate with other database table.<br>If press \"Remove\" system will remove all data from relation.");
        sb.append("        </td>");
        sb.append("    </tr>");
        sb.append("    <tr><td class=\"text\" align=\"center\" colspan=\"2\">");
        sb.append("           <input type=\"button\" value=\"Remove\" class=\"button\" onclick=\"javascript:remove(this.form,'" + onclickurl + "');\" />&nbsp;");
        sb.append("           <input type=\"button\" value=\"Cancel\" class=\"button\" onclick=\"javascript:history.go(-1);\"/>");
        sb.append("         </td>");
        sb.append("    </tr>");
        sb.append("  </table>");
        return sb.toString();
    }

    public String getPrefixFileName() {
        StringBuffer ud = new StringBuffer();
        NumberFormat formatter = new DecimalFormat("00");
        Calendar rightNow = Calendar.getInstance();
        ud.append(formatter.format(rightNow.get(Calendar.YEAR)));
        ud.append(formatter.format(rightNow.get(Calendar.MONTH) + 1));
        ud.append(formatter.format(rightNow.get(Calendar.DAY_OF_MONTH)));
        ud.append(formatter.format(rightNow.get(Calendar.HOUR_OF_DAY)));
        ud.append(formatter.format(rightNow.get(Calendar.MINUTE)));
        ud.append(formatter.format(rightNow.get(Calendar.SECOND)));
        ud.append(formatter.format(rightNow.get(Calendar.MILLISECOND)));
        return ud.toString();
    }

    public static String getBookId(int num) {
        StringBuffer buf = new StringBuffer();
        buf.append(num);
        while (buf.length() <= 7) {
            buf.insert(0, 0);
        }
        return buf.toString();
    }
    private String prefix2 = "%u0E";//tai ok
    static char ciis[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
        'a', 'b', 'c', 'd', 'e', 'f'
    };
    public String encode(String s) {
        StringBuffer buf = new StringBuffer();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            buf.append(encoding(c));
        }
        return buf.toString();
    }

    public String encoding(char c) {
       // if (c == '-') {
//            System.out.println("ccc>>"+c);
       // }
        if ((int) c < 3585 || (int) c > 3675) {
            //return "%" + Integer.toHexString((int) c);
            return "%00%" + Integer.toHexString((int) c);//090713
        }
        for (int i = 3585, j = 0, k = 1; i < 3676; i++) {
            if (c == ((char) i)) {
                return prefix2 + ciis[j] + ciis[k];
            }
            if (k == (ciis.length - 1)) {
                k = 0;
                j++;
            } else {
                k++;
            }

            if (j == (ciis.length - 1)) {
                j = 0;
            }
        }
        return c + "";
    }
}
